<?php
// +-------------+-------------+------+-----+---------+----------------+
// | Field       | Type        | Null | Key | Default | Extra          |
// +-------------+-------------+------+-----+---------+----------------+
// | id          | int(11)     | NO   | PRI | NULL    | auto_increment |
// | uid         | int(11)     | NO   | MUL | 0       |                |
// | group_id    | int(11)     | NO   | MUL | 0       |                |
// | create_time | int(11)     | NO   |     | 0       |                |
// | update_time | int(11)     | NO   |     | 0       |                |
// | editor_id   | int(11)     | YES  |     | 0       |                |
// | user_type   | varchar(10) | YES  |     |         |                |
// +-------------+-------------+------+-----+---------+----------------+
namespace app\common\model;
use think\Request;
use think\Loader;
use app\common\model\AdminBase;
class GroupAccess extends AdminBase{
  /**
   * 添加或更新用户所在组
   * @Author zhanghong
   * @Date   2017-04-23
   * @param  integer    $user_id   用户ID
   * @param  integer    $group_id  所在组ID
   * @param  string     $user_type 所在组类型
   * @return array
   */
  public function createOrUpdateUserAccess($user_id, $group_id, $user_type){
    $res = array("status" => false, "msg" => "更新用户组失败");
    $data = ["uid" => $user_id, "user_type" => $user_type, "group_id" => $group_id];

    $item = $this->where("uid", $user_id)->where("user_type", $user_type)->find();
    $validate = Loader::validate("GroupAccess");
    if($validate->check($data)){
      if(empty($item)){
        $this->data($data);
        $this->save();
      }else if($item["group_id"] != $group_id){
        // 用户组变化了，更新数据
        $this->update($data, ['id' => $item["id"]]);
      }
      $res = array("status" => true, "msg" => "更新用户组成功");
    }else{
      $res["msg"] = $validate->getError();
    }
    return $res;
  }

  /**
   * 删除用户所在群组
   * @Author zhanghong
   * @Date   2017-04-23
   * @param  integer    $user_id    用户ID
   * @param  string     $user_type  用户组类型
   * @return true
   */
  public function deleteUserAccess($user_id, $user_type){
    $this->where("uid", $user_id)->where("user_type", $user_type)->delete();
  }
}